package com.cloudcc.mobile.view.nearby;

import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.util.NearByUtil;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.NearByListAdapter;
import com.cloudcc.mobile.adapter.NearByListTianAdapter;
import com.cloudcc.mobile.dao.CallLogDao;
import com.cloudcc.mobile.dao.impl.CallLogDaoImpl;
import com.cloudcc.mobile.dialog.CallLogLoadingDialog;
import com.cloudcc.mobile.dialog.NearBYCompanyChangeDialog;
import com.cloudcc.mobile.dialog.NearByGoolePopupwindow;
import com.cloudcc.mobile.entity.NearByFilterEntity;
import com.cloudcc.mobile.entity.TianYanEntity;
import com.cloudcc.mobile.entity.TwoOb;
import com.cloudcc.mobile.entity.map.NearByMapInfo;
import com.cloudcc.mobile.event.BeauEventList;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.presenter.BeauPresenter;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.view.activity.BeauInfoActivity;
import com.cloudcc.mobile.view.activity.NearByMapScreenActivity;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationAvailability;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.ParseException;
import org.json.JSONArray;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;


/**
 * Created by lin on 2017/5/8.
 */


public class NearByGoogleMapActivity extends BaseActivity implements View.OnClickListener, NearByGoolePopupwindow.onItemPopupClick, IEventLife ,OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
        GoogleMap.OnMarkerClickListener, LocationListener {


    @Bind(R.id.near_by_back_iv)
    ImageView nearByBackIv;
    @Bind(R.id.near_by_list_iv)
    ImageView nearByListIv;
    @Bind(R.id.near_by_title_long_tv)
    TextView nearByTitleLongTv;
    @Bind(R.id.near_by_title_long_iv)
    ImageView nearByTitleLongIv;
    @Bind(R.id.near_by_title_long_layout)
    LinearLayout nearByTitleLongLayout;
    @Bind(R.id.near_by_title_lei_tv)
    TextView nearByTitleLeiTv;
    @Bind(R.id.near_by_title_lei_iv)
    ImageView nearByTitleLeiIv;
    @Bind(R.id.near_by_title_lei_layout)
    LinearLayout nearByTitleLeiLayout;
    @Bind(R.id.near_by_map_top_layout)
    RelativeLayout nearByMapTopLayout;
    @Bind(R.id.near_by_top_line)
    View nearByTopLine;
    @Bind(R.id.near_by_location_tv)
    TextView nearByLocationTv;
    @Bind(R.id.near_by_refresh_iv)
    ImageView nearByRefreshIv;
    @Bind(R.id.near_by_number_tv)
    TextView nearByNumberTv;
    @Bind(R.id.near_by_list)
    ListView nearByList;
    @Bind(R.id.near_by_custom_name_tv)
    TextView nearByCustomNameTv;
    @Bind(R.id.near_by_custom_long_tv)
    TextView nearByCustomLongTv;
    @Bind(R.id.near_by_detail_layout)
    LinearLayout nearByDetailLayout;
    @Bind(R.id.near_by_route_layout)
    LinearLayout nearByRouteLayout;
    @Bind(R.id.near_by_custom_layout)
    LinearLayout nearByCustomLayout;
    @Bind(R.id.near_by_map_all)
    LinearLayout nearByMapAll;
    @Bind(R.id.near_by_long_tv)
    TextView nearByLongTv;
    @Bind(R.id.near_by_object_tv)
    TextView nearByObjectTv;
    @Bind(R.id.near_by_bottom_screen)
    LinearLayout nearByBottomScreen;
    @Bind(R.id.near_by_nodata_layout)
    LinearLayout nearByNoData;
    @Bind(R.id.near_by_yindao1)
    RelativeLayout nearByYindao1;
    @Bind(R.id.near_by_yindao2)
    RelativeLayout nearByYindao2;
//    @Bind(R.id.near_by_map_google)
    SupportMapFragment nearByMap;

    private NearByGoolePopupwindow popupdis, popupobj;
    private boolean firstLocation;//是否是首次定位
    private BitmapDescriptor mCurrentMarker;
    private MyOrientationListener myOrientationListener;

    private double mCurrentLantitude, mCurrentLongitude;//当前经纬度
    private String addressNow;//当前定位地址
    private float mCurrentAccracy;//getRadius 获取定位精度,默认值0.0f
    private float mXDirection;//定位选择角度，设定图标方向
    private String mEns = RunTimeManager.getInstance().getlanguage();
    private Bitmap bitmapDescriptor1, bitmapDescriptorSelect1;
    private BitmapDescriptor bitmapDescriptor, bitmapDescriptorSelect;

    private LatLng formlatLng;//起始经纬度
    private LatLng tolatLng;//目的地经纬度

    private List<NearByMapInfo.NearByMapInfo2> lists = new ArrayList<>();

    public static boolean isMap = true;//判断当前显示的是否是地图，默认显示地图
    private NearByListAdapter adapter;
    private NearByListTianAdapter adapterTian;
    private int marks;//1--打开第一个pop  2--打开第二个pop

    private List<NearByFilterEntity> onelist = new ArrayList<>();

    private String oneName, twoName, addressSub;//筛选条件
    private String objects = "001";//默认初始客户
    private String distances = "3000";//默认初始3km

    private CallLogDao callLogDao;//请求服务器的封装方法类
    private List<TianYanEntity.DataBean> nearComlists = new ArrayList<>();
    private boolean isNearByCom = false;//是否是附近公司选项

    SharedPreferences yindaoShare;//记录是否第一次登陆，是否需要引导
    private boolean isFirst = true, isFirstList = true;
    private CallLogLoadingDialog loadingDialog;
    private NearBYCompanyChangeDialog changeDialog;//附近公司改变地图模式时提醒
    private String comIds;
    private boolean isSelect = false;

    private BeauPresenter.FilterCondition mFilterCondition = null;//查询客户和潜在客户公司的返回bean
    private BeauPresenter mBeauPresenter = new BeauPresenter();//请求潜在客户和客户的接口封装类


    //google新加
    private GoogleMap mMap;
    private GoogleApiClient mGoogleApiClient;
    private Location mLastLocation;
    private LocationRequest mLocationRequest;
    private boolean mLocationUpdateState;
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
    private static final int REQUEST_CHECK_SETTINGS = 2;
    private static final int PLACE_PICKER_REQUEST = 3;

    @Override
    public void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);

        register();
        initView();
        initLister();
        jiexiJson();
        listtomap();

    }

    /**
     * 初始化view、地图、定位
     */
    private void initView() {
        mFilterCondition = new BeauPresenter.FilterCondition();

        loadingDialog = new CallLogLoadingDialog(this,R.style.DialogLoadingTheme);
        changeDialog = new NearBYCompanyChangeDialog(this,R.style.DialogLoadingTheme);
        yindaoShare = getSharedPreferences("NearByYinDao", 0);
        isFirst = yindaoShare.getBoolean("IsFirst", true);

        callLogDao = new CallLogDaoImpl();
        popupdis = new NearByGoolePopupwindow(this, 1);//距离弹窗
        popupobj = new NearByGoolePopupwindow(this, 2);//对象弹窗
        bitmapDescriptor1 = BitmapFactory.decodeResource(getResources(), R.drawable.nearby_positionicon);
        adapter = new NearByListAdapter(this);
        adapterTian = new NearByListTianAdapter(this);
        nearByList.setAdapter(adapter);

        nearByMap.getMapAsync(this);

        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
        }

        createLocationRequest();
        firstLocation = true;

        if (isFirst) {
            nearByYindao1.setVisibility(View.VISIBLE);
        } else {
            nearByYindao1.setVisibility(View.GONE);
            nearByYindao2.setVisibility(View.GONE);
        }
    }


    private void initLister() {
        nearByTitleLongLayout.setOnClickListener(this);
        nearByTitleLeiLayout.setOnClickListener(this);
        nearByBackIv.setOnClickListener(this);
        nearByListIv.setOnClickListener(this);
        nearByDetailLayout.setOnClickListener(this);
        nearByRouteLayout.setOnClickListener(this);
        nearByBottomScreen.setOnClickListener(this);
        nearByRefreshIv.setOnClickListener(this);
        nearByYindao1.setOnClickListener(this);
        nearByYindao2.setOnClickListener(this);

        nearByList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (!isNearByCom) {
                    Intent intent = new Intent(NearByGoogleMapActivity.this, BeauInfoActivity.class);
                    intent.putExtra("web", lists.get(position).getId());
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(NearByGoogleMapActivity.this, NearByCompanyActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("data", nearComlists.get(position));
                    intent.putExtra("databundle", bundle);
                    startActivity(intent);
                }
            }
        });

        setMarkerClick();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_nearby_map_google;
    }

    @Override
    public void onClick(View v) {
        if (v == nearByTitleLongLayout) {
            if (popupdis.isShowing()) {
                popupdis.dismiss();
            } else {
                marks = 1;
                NearByUtil.startPropertyAnim(nearByTitleLongIv);
                popupdis.showPopupWindow(nearByMapAll, nearByBackIv.getWidth() + (nearByTitleLongLayout.getWidth() / 2), nearByMapTopLayout, NearByUtil.getStatusBarHeight(this));
            }
        }
        if (v == nearByTitleLeiLayout) {
            if (popupobj.isShowing()) {
                popupobj.dismiss();
            } else {
                marks = 2;
                NearByUtil.startPropertyAnim(nearByTitleLeiIv);
                popupobj.showPopupWindow(nearByMapAll, nearByBackIv.getWidth() + nearByTitleLongLayout.getWidth() + (nearByTitleLeiLayout.getWidth() / 2), nearByMapTopLayout, NearByUtil.getStatusBarHeight(this));
                popupobj.setDataToView();
            }
        }
        if (v == nearByBackIv) {
//            finish();
            Intent intent = new Intent(this,NearByGoogleMapActivity.class);
            startActivity(intent);
        }
        if (v == nearByListIv) {
            if (isMap) {
                isFirstList = yindaoShare.getBoolean("isFirstList", true);
                if (isFirstList) {
                    nearByYindao2.setVisibility(View.VISIBLE);
                    return;
                }
                maptolist();
                setListParger();
                nearByBottomScreen.setVisibility(View.GONE);
            } else {
                if (!isNearByCom) {
                    listtomap();
                    addInfosOverlay();
                }else {
                    changeDialog.show();
                }
            }

        }
        if (v == nearByDetailLayout) {
            Intent intent = new Intent(this, BeauInfoActivity.class);
            intent.putExtra("web", comIds);
            startActivity(intent);
        }
        if (v == nearByRouteLayout) {
            if (NearByUtil.isInstallByRead("com.baidu.BaiduMap")) {
                NearByUtil.startBaiduMap(tolatLng.latitude + "", tolatLng.longitude + "", this);
            } else if (NearByUtil.isInstallByRead("com.autonavi.minimap")) {
                NearByUtil.startGaode(tolatLng.latitude + "", tolatLng.longitude + "", this);
            } else {
                Toast.makeText(this, R.string.gaodemaptoast, Toast.LENGTH_SHORT).show();
            }
        }
        if (v == nearByBottomScreen) {//筛选界面
            Intent intent = new Intent(this, NearByMapScreenActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("data", (Serializable) onelist);
            intent.putExtra("bundata", bundle);
            startActivityForResult(intent, 1008);
        }
        if (v == nearByRefreshIv) {
//            firstLocation = true;//设置为首次定位地图
            if (isNearByCom) {
                getTianyanData();//获取附近公司信息
            } else {
                getNearbyData();
            }
        }
        if (v == nearByYindao1) {
            SharedPreferences.Editor editor = yindaoShare.edit();
            editor.putBoolean("IsFirst", false);
            editor.commit();
            nearByYindao1.setVisibility(View.GONE);
        }
        if (v == nearByYindao2) {
            nearByYindao2.setVisibility(View.GONE);
            SharedPreferences.Editor editor = yindaoShare.edit();
            editor.putBoolean("isFirstList", false);
            editor.commit();
            //继续执行地图转列表页的操作
            maptolist();
            setListParger();
            nearByBottomScreen.setVisibility(View.GONE);
        }
    }

    //列表页转地图界面
    private void listtomap() {
        nearByListIv.setImageResource(R.drawable.nearby_listlookover);
        nearByList.setVisibility(View.GONE);
        nearByNoData.setVisibility(View.GONE);
        nearByMap.onHiddenChanged(false);
        nearByBottomScreen.setVisibility(View.GONE);
        isMap = true;
    }

    //地图界面转列表页
    private void maptolist() {
        nearByListIv.setImageResource(R.drawable.nearby_maplookover);
        nearByCustomLayout.setVisibility(View.GONE);
        nearByMap.onHiddenChanged(true);
        nearByList.setVisibility(View.VISIBLE);
        isMap = false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            oneName = data.getStringExtra("onename");
            twoName = data.getStringExtra("twoname");
            getTianyanData();
        }
    }

    /**
     * 顶部popup选择结果
     */
    @Override
    public void onItemPopupClick(int obj, int mark) {
        nearByCustomLayout.setVisibility(View.GONE);//隐藏显示的选中图层详细信息
        isSelect = false;//设置选择为未选择
        if (mark == 1) {
            switch (obj) {
                case R.string.near_by_1km:
                    distances = "1000";
                    break;
                case R.string.near_by_3km:
                    distances = "3000";
                    break;
                case R.string.near_by_5km:
                    distances = "5000";
                    break;
                case R.string.near_by_maxkm:
                    distances = "10000";
                    break;
            }
            if (!isNearByCom) {//如果不是附近公司需请求服务器刷新数据
                getNearbyData();
            }
            nearByTitleLongTv.setText(getString(obj));
            nearByLongTv.setText(getString(obj));
            popupdis.dismiss();
        } else {
            switch (obj) {
                case R.string.near_by_ob1:
                    isNearByCom = true;//设置为附近公司模式
                    maptolist();//设置为列表显示
                    nearByBottomScreen.setVisibility(View.VISIBLE);
                    getTianyanData();//获取附近公司信息
                    break;
                case R.string.near_by_ob2:
                    objects = "003";
                    isNearByCom = false;//设置不是附近公司
                    break;
                case R.string.near_by_ob3:
                    objects = "001";
                    isNearByCom = false;//设置不是附近公司
                    break;
                case R.string.near_by_ob4:
                    objects = "002";
                    isNearByCom = false;//设置不是附近公司
                    break;
                case R.string.near_by_ob5:
                    objects = "004";
                    isNearByCom = false;//设置不是附近公司
                    break;
            }
            if (!isNearByCom) {
                nearByBottomScreen.setVisibility(View.GONE);
                getNearbyData();//请求刷新数据
            }
            nearByTitleLeiTv.setText(getString(obj));
            if ("en".equals(mEns)) {
                nearByObjectTv.setText(getString(obj));
            } else {
                nearByObjectTv.setText("个" + getString(obj));
            }
            popupobj.dismiss();
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        nearByMap = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.near_by_map_google);
    }

    @Override
    protected void onStop() {
        // 关闭图层定位
        if( mGoogleApiClient != null && mGoogleApiClient.isConnected() ) {
            mGoogleApiClient.disconnect();
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 在activity执行onDestroy时执行mMapView.onDestroy()
        nearByMap.onDestroy();
        nearByMap = null;
        unRegister();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 在activity执行onResume时执行mMapView. onResume ()
        if (mGoogleApiClient.isConnected() && !mLocationUpdateState) {
            startLocationUpdates();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient, this);
    }

    @Override
    protected void onStart() {
        // 如果要显示位置图标,必须先开启图层定位
        mGoogleApiClient.connect();// 连接Google Play服务
        super.onStart();
    }


    /**
     * 初始化图层
     */
    public void addInfosOverlay() {
        LatLng latLng = null;
        Marker marker = null;
        mMap.clear();
        if (lists != null && lists.size() != 0) {

            for (int n = 0; n < lists.size(); n++) {
                NearByMapInfo.NearByMapInfo2 info = lists.get(n);
                // 位置
                latLng = new LatLng(info.getLatitude(), info.getLangitude());
                // 图标
                if (n == 0 && !isSelect) {//默认未做选择之前选中第一个
                    bitmapDescriptorSelect1 = BitmapFactory.decodeResource(getResources(), R.drawable.nearby_positionicon_selected);
                    bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(NearByUtil.createDrawable(n + 1 + "", bitmapDescriptorSelect1, R.color.near_by_tubiao_text_color_select, NearByGoogleMapActivity.this));
                } else {
                    bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(NearByUtil.createDrawable(n + 1 + "", bitmapDescriptor1, R.color.near_by_tubiao_text_color, NearByGoogleMapActivity.this));
                }
                MarkerOptions markerOptions = new MarkerOptions().position(latLng).icon(bitmapDescriptor).title(n + 1 + "");
                marker = mMap.addMarker(markerOptions);
                marker.setTitle(n + 1 + "");
                marker.setPosition(latLng);
                marker.setSnippet(n+"");
                tolatLng = latLng;

                if (n == 0 && !isSelect) {//默认未做选择之前显示第一个的详情信息
                    nearByCustomLayout.setVisibility(View.VISIBLE);
                    nearByCustomNameTv.setText((info.getName() == null ? "" :  n + 1+"."+info.getName()));
                    String distanceNow = String.format(getResources().getString(R.string.near_by_now_distance), getDistance_km(tolatLng, formlatLng));
                    nearByCustomLongTv.setText(distanceNow);
                    comIds = info.getId();
                }
            }
        }
        // 将地图移到到最后一个经纬度位置
//        MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(latLng);
//        baiduMap.setMapStatus(u);
    }

    //设置图层点击事件
    private void setMarkerClick() {
        mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(final Marker marker) {
                isSelect = true;
                addInfosOverlay();
                //获得marker中的数据
                String titles = marker.getTitle();

                int pos = Integer.parseInt(marker.getSnippet());
                NearByMapInfo.NearByMapInfo2 info = lists.get(pos);

                // 位置
                LatLng latLng = marker.getPosition();
                bitmapDescriptorSelect1 = BitmapFactory.decodeResource(getResources(), R.drawable.nearby_positionicon_selected);
                bitmapDescriptorSelect = BitmapDescriptorFactory.fromBitmap(NearByUtil.createDrawable(titles, bitmapDescriptorSelect1, R.color.near_by_tubiao_text_color_select, NearByGoogleMapActivity.this));
                // 图标
                MarkerOptions markerOptions = new MarkerOptions().position(latLng).icon(bitmapDescriptorSelect).title(titles);
                Marker marker2 = mMap.addMarker(markerOptions);
                marker2.setTitle(titles);
                marker2.setPosition(latLng);
                marker2.setSnippet(info.getName());
                tolatLng = latLng;

                nearByCustomLayout.setVisibility(View.VISIBLE);
                nearByCustomNameTv.setText((info.getName() == null ? "" : titles+"."+info.getName()));
                String distanceNow = String.format(getResources().getString(R.string.near_by_now_distance), getDistance_km(tolatLng, formlatLng));
                nearByCustomLongTv.setText(distanceNow);
                comIds = info.getId();

                return true;
            }
        });
    }

    /**
     * 计算两点之间距离
     *
     * @return 米
     */
    private String getDistance_km(LatLng mudilng, LatLng melng) {

        double distanse = getDistance(mudilng, melng);
        distanse = Math.floor(distanse);
        String temp = "";

        //转换成公里
//        if (distanse < 1000) {
        temp = distanse + "m"; //距离误差大小为500米以内
//        } else {
//            temp = String.format("%.2f", (distanse) / 1000) + "km";
//        }

        return temp;
    }

    public void changeAnima() {//顶部三角转回动画
        if (marks == 1) {
            NearByUtil.startPropertyAnim2(nearByTitleLongIv);
        } else if (marks == 2) {
            NearByUtil.startPropertyAnim2(nearByTitleLeiIv);
        }

    }

    private String getJson() {//获取本地json（筛选数据）
        StringBuffer buffer = new StringBuffer("");
        try {
            InputStream is = getAssets().open("filternearby.json");//此处为要加载的json文件名称
            InputStreamReader reader = new InputStreamReader(is);
            BufferedReader bufferedReader = new BufferedReader(reader);
            String str;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
        }
        return buffer.toString();
    }


    private void jiexiJson() {//解析本地json（筛选数据）
        String jsons = getJson();
        JSONArray array = null;
        JSONObject object;
        JSONArray jsonArray;
        JSONObject objecttwo;

        try {
            array = new JSONArray(jsons);
            onelist.clear();
            for (int i = 0; i < array.length(); i++) {
                object = array.optJSONObject(i);
                jsonArray = object.optJSONArray("twolist");
                List<TwoOb> twolist = new ArrayList<>();
                for (int j = 0; j < jsonArray.length(); j++) {
                    objecttwo = jsonArray.optJSONObject(j);
                    twolist.add(new TwoOb(objecttwo.optString("twoname")));
                }
                onelist.add(new NearByFilterEntity(object.optString("onename"), twolist));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    //获取天眼查的数据
    private void getTianyanData() {
        loadingDialog.show();
        loadingDialog.settext(getString(R.string.xsearch_loading));
        String url = "https://open.api.tianyancha.com/services/v3/newopen/search.json";
        RequestParams params = new RequestParams();
        if (oneName == null || oneName.equals("不限")) {
            oneName = "";
        }
        if (twoName == null || twoName.equals("不限")) {
            twoName = "";
        }
        if (addressSub == null) {
            addressSub = "";
        }
        params.put("word", oneName + twoName + addressSub);
        BeauEventList.NearByTianYanChaEvent Event = new BeauEventList.NearByTianYanChaEvent();
        Header header = new Header() {
            @Override
            public String getName() {
                return "Authorization";
            }

            @Override
            public String getValue() {
                return "AnHanne8ayAI";
            }

            @Override
            public HeaderElement[] getElements() throws ParseException {
                return new HeaderElement[0];
            }
        };
        Header[] headers = {header};
        callLogDao.getTianYanCha(this, url, headers, params, Event);
    }

    @Override
    public void register() {
        EventEngine.register(this);
    }

    @Override
    public void unRegister() {
        EventEngine.uregister(this);
    }

    private int num = 0;
    private  String objectIds = "lead";
    //天眼查返回附近公司数据
    public void onEventMainThread(BeauEventList.NearByTianYanChaEvent event) {
        loadingDialog.dismiss();
        if (event.isError()) {
            nolist();
            return;
        }
        String data = event.getData();
        if (data == null) {
            nolist();
            return;
        }
        Gson mGson = new Gson();
        TianYanEntity tianYanEntity = mGson.fromJson(data, TianYanEntity.class);
        if (tianYanEntity.getState().equals("ok")) {

            nearComlists = tianYanEntity.getData();
            if (nearComlists == null || nearComlists.size() == 0) {
                nolist();
                return;
            }
            num = 0;
            String names = (nearComlists.get(0).getName()).replaceAll("</em>","");
            names = names.replaceAll("<em>","");
            getLead(names,objectIds);

        } else {
            nolist();
        }
    }

    public void onEventMainThread(BeauEventList.BeauListEvent event) {

        if(event.getData() != null && event.getData().size() > 0){//如果有数据删除当前这条
            objectIds = "lead";
            nearComlists.remove(num);
        }else {
            if(objectIds.equals("lead")){//如果是检查的潜在客户下次查客户
                objectIds = "account";
            }else{//如果是查的客户，下次查下一条
                objectIds = "lead";
                num++;
            }
        }
        jiegou();

    }

    //结果处理
    private void jiegou(){
        if(num < nearComlists.size()){
            String names = (nearComlists.get(num).getName()).replaceAll("</em>","");
            names = names.replaceAll("<em>","");
            getLead(names,objectIds);
        }else{
            if(nearComlists == null || nearComlists.size() == 0){
                loadingDialog.dismiss();
                nolist();
            }else {
                loadingDialog.dismiss();
                nearByList.setVisibility(View.VISIBLE);
                nearByNoData.setVisibility(View.GONE);
                nearByList.setAdapter(adapterTian);
                adapterTian.clear();
                adapterTian.addData(nearComlists);
                nearByNumberTv.setText(nearComlists.size() + "");
            }
        }
    }

    //请求查看附近公司是否是客户或潜在客户公司
    private void getLead(String names , String objectId) {
        mFilterCondition.pageNum = 1;

        mFilterCondition.viewId = "";
        // 排序
        mFilterCondition.objectId = objectId;
        // 关键字
        mFilterCondition.keyword = names;

        mBeauPresenter.getBeanList(mFilterCondition);
        mFilterCondition.filterFileds.clear();
    }

    //请求服务器返回附近对象数据
    public void onEventMainThread(BeauEventList.NearByObjectEvent event) {
//        loadingDialog.dismiss();
        if (event.isError()) {
            if (!isMap) {
                nolist();
            }
            nearByNumberTv.setText("0");
            return;
        }
        NearByMapInfo nearByMapInfo = event.getData();
        lists = nearByMapInfo.getData();
        if (isMap) {//当前显示为地图界面
            addInfosOverlay();
        } else {//当前显示为列表页面
            setListParger();
        }
        if (lists == null || lists.size() == 0) {
            nearByNumberTv.setText("0");
        } else {
            nearByNumberTv.setText(lists.size() + "");
        }
    }

    private void setListParger() {
        if (lists == null || lists.size() == 0) {
            nolist();
            return;
        }
        for(int n = 0; n < lists.size() ; n++){
            NearByMapInfo.NearByMapInfo2 info = lists.get(n);
            tolatLng = new LatLng(info.getLatitude(), info.getLangitude());
            String distances = getDistance_km(tolatLng,formlatLng);
            info.setDistance(distances);
        }
        nearByList.setVisibility(View.VISIBLE);
        nearByNoData.setVisibility(View.GONE);
        nearByList.setAdapter(adapter);
        adapter.clear();
        adapter.addData(lists);
    }

    //获取附近对应对象的数据
    private void getNearbyData() {
        BeauEventList.NearByObjectEvent event = new BeauEventList.NearByObjectEvent();
        callLogDao.getNearbyObjects(objects, mCurrentLantitude + "", mCurrentLongitude + "", distances, event);
    }

    //列表数据为空时
    private void nolist() {
        nearByList.setVisibility(View.GONE);
        nearByNoData.setVisibility(View.VISIBLE);
        nearByNumberTv.setText("0");
    }

    @Override
    public void onConnected(Bundle bundle) {
        setUpMap();
        if (mLocationUpdateState) {
            startLocationUpdates();
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        return false;
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.setOnMarkerClickListener(this);
    }

    /**
     * 计算两点之间距离
     * @param start
     * @param end
     * @return 米
     */
    public double getDistance(LatLng start,LatLng end){
        double lat1 = (Math.PI/180)*start.latitude;
        double lat2 = (Math.PI/180)*end.latitude;

        double lon1 = (Math.PI/180)*start.longitude;
        double lon2 = (Math.PI/180)*end.longitude;

//      double Lat1r = (Math.PI/180)*(gp1.getLatitudeE6()/1E6);
//      double Lat2r = (Math.PI/180)*(gp2.getLatitudeE6()/1E6);
//      double Lon1r = (Math.PI/180)*(gp1.getLongitudeE6()/1E6);
//      double Lon2r = (Math.PI/180)*(gp2.getLongitudeE6()/1E6);

        //地球半径
        double R = 6371;

        //两点间距离 km，如果想要米的话，结果*1000就可以了
        double d =  Math.acos(Math.sin(lat1)*Math.sin(lat2)+Math.cos(lat1)*Math.cos(lat2)*Math.cos(lon2-lon1))*R;

        return d*1000;
    }

    private void setUpMap() {
        if (ActivityCompat.checkSelfPermission(this,
                android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
            return;
        }

        mMap.setMyLocationEnabled(true); // 1

        LocationAvailability locationAvailability =
                LocationServices.FusedLocationApi.getLocationAvailability(mGoogleApiClient); // 2
        if (null != locationAvailability && locationAvailability.isLocationAvailable()) {
            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); // 3

            if (mLastLocation != null) {    // 4
                LatLng currentLocation = new LatLng(mLastLocation.getLatitude(), mLastLocation
                        .getLongitude());
                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 12));

                addressNow = getAddress(currentLocation);
                addressSub = Tools.subAddress(addressNow);
                if(addressSub.contains("中国")){
                    addressSub = addressSub.substring(2);
                }

                formlatLng = currentLocation;

                if (firstLocation) {
                    addressNow = String.format(getResources().getString(R.string.near_by_now_location), addressNow);
                    nearByLocationTv.setText(addressNow);
                    firstLocation = false;
                    getNearbyData();
                }
            }
        }
    }

    protected void startLocationUpdates() {
        if (ActivityCompat.checkSelfPermission(this,
                android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
    }

    private String getAddress( LatLng latLng ) {
        Geocoder geocoder = new Geocoder( this ); // 1
        String addressText = "";
        List<Address> addresses = null;
        Address address = null;
        try {
            addresses = geocoder.getFromLocation( latLng.latitude, latLng.longitude, 1 ); // 2
            if (null != addresses && !addresses.isEmpty()) { // 3
                address = addresses.get(0);
                for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                    addressText += (i == 0)?address.getAddressLine(i):("\n" + address.getAddressLine(i));
                }
            }
        } catch (IOException e ) {
        }
        return addressText;
    }

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(10000);
        mLocationRequest.setFastestInterval(5000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(mLocationRequest);

        PendingResult<LocationSettingsResult> result =
                LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient,
                        builder.build());

        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(@NonNull LocationSettingsResult result) {
                final Status status = result.getStatus();
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        mLocationUpdateState = true;
                        startLocationUpdates();
                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        try {
                            status.startResolutionForResult(NearByGoogleMapActivity.this, REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException e) {
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        break;
                }
            }
        });
    }

}
